package com.lzc.jobrecomendbackend.service.education.impl;

import com.lzc.jobrecomendbackend.model.Job;
import com.lzc.jobrecomendbackend.model.education.EducationDistributionVO;
import com.lzc.jobrecomendbackend.repository.JobRepository;
import com.lzc.jobrecomendbackend.service.education.EducationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EducationServiceImpl implements EducationService {

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<EducationDistributionVO> getEducationDistribution(String city, String companySize) {
        // 构建查询条件
        Criteria criteria = new Criteria();
        
        // 添加筛选条件
        if (city != null && !city.isEmpty()) {
            criteria.and("工作城市").is(city);
        }
        if (companySize != null && !companySize.isEmpty()) {
            criteria.and("公司规模").is(companySize);
        }
        
        // 使用聚合查询统计各学历要求的职位数量
        Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.match(criteria),
            Aggregation.group("学历要求").count().as("count"),
            Aggregation.project("count").and("_id").as("education")
        );
        
        AggregationResults<Map> results = mongoTemplate.aggregate(
            aggregation, "jobs", Map.class
        );
        
        // 转换为视图对象列表
        List<EducationDistributionVO> distributionList = new ArrayList<>();
        for (Map result : results.getMappedResults()) {
            String education = (String) result.get("education");
            Integer count = ((Number) result.get("count")).intValue();
            
            // 处理可能的null值
            if (education == null || education.isEmpty()) {
                education = "不限";
            }
            
            distributionList.add(new EducationDistributionVO(education, count));
        }
        
        return distributionList;
    }
} 